import { createRouter, createWebHashHistory } from "vue-router";

export const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            name: 'login',
            component: () => import('../views/login/Index.vue'),
            meta: {
                requiresAuth: false
            }
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/home/Index.vue'),
            children: [
                {
                    path: 'dashboard',
                    name: 'dashboard',
                    component: () => import('../views/dashboard/Index.vue')
                },
                {
                    path: 'monitor',
                    name: 'monitor',
                    component: () => import('../views/dashboard/Monitor.vue')
                },
                {
                    path: '/404',
                    name: 'notFound',
                    component: () => import('../views/error/404.vue')
                }
            ],
            meta: {
                requiresAuth: true
            }
        }
    ],
})

router.beforeEach((to, from, next) => {
    if (to.name === 'login') {
        if ((to.meta.length > 0 && !to.meta.requiresAuth)) {
            next()
        }
        let Auth = localStorage.getItem('X-SEER-AUTH')
        if (Auth) {
            next({ name: 'home' })
        }
        next()
    }

    if (to.path !== '/login') {
        let Auth = localStorage.getItem('X-SEER-AUTH')
        if (Auth) {
            if (to.matched.length !== 0) {
                next()
            } else {
                next({ name: 'notFound' })
            }
        } else {
            localStorage.removeItem('X-SEER-AUTH')
            next({ name: 'login' })
        }
    } else {
        localStorage.removeItem('X-SEER-AUTH')
        next({ name: 'login' })
    }
})